/*******************************************************************************
 * $Header$
 * $Revision$
 * $Date$
 *
 *==============================================================================
 *
 * Copyright©hxlife/hulife 
 * All rights reserved.
 * 
 * Created on 2017年9月19日
 *******************************************************************************/

package com.hualife.support.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Map;

/**
 * @description: TODO 此处填写 class 信息
 * @author 孙小冬 (mailto:sunxiaodong001@hualife.cc)
 */
public class SignatureUtil {

	private static final String ENCODING = "UTF-8";

	private static final String SEPARATOR_AND = "&";

	private static final String SEPARATOR_EQUAL = "=";

	private static String percentEncode(String value, String encode)
			throws UnsupportedEncodingException {
		return value != null ? URLEncoder.encode(value, encode)
				.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
				: null;
	}

	public static String sign(Map<String, String> parameters, String privateKey)
			throws UnsupportedEncodingException {
		return sign(parameters, privateKey, ENCODING);
	}

	public static String sign(Map<String, String> parameters,
			String privateKey, String encode)
			throws UnsupportedEncodingException {
		// 对参数进行排序
		String[] sortedKeys = parameters.keySet().toArray(new String[] {});
		Arrays.sort(sortedKeys);

		// 生成stringToSign字符串
		StringBuilder stringToSign = new StringBuilder();
		stringToSign.append(privateKey);

		StringBuilder canonicalizedQueryString = new StringBuilder();
		for (String key : sortedKeys) {
			// 这里注意对key和value进行编码
			canonicalizedQueryString.append(SEPARATOR_AND)
					.append(percentEncode(key, encode)).append(SEPARATOR_EQUAL)
					.append(percentEncode(parameters.get(key), encode));
		}

		// 这里注意对canonicalizedQueryString进行编码
		stringToSign.append(percentEncode(canonicalizedQueryString.toString(),
				encode));
		String sign = MD5Util.sign(stringToSign.toString(), encode);
		System.out.println(stringToSign + "-------------" + sign);
		return sign;
	}
}

/*
 * 修改历史 $Log$
 */